package com.drop.service.impl;

import com.drop.dao.CartDao;
import com.drop.dao.CommonDao;
import com.drop.entity.Cart;
import com.drop.service.CartService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by 陈东一 on 2017/9/23 16:29
 */
@Service
@Transactional
public class CartServiceImpl implements CartService {

	private Log log = LogFactory.getLog(this.getClass());

	@Autowired
	private CommonDao commonDao;

	@Autowired
	private CartDao cartDao;

	@Override
	public Boolean addCart(int userId, int itemId, int num) {
		Cart cart = cartDao.getCartByUserAndItem(userId, itemId);
		//如果购物车中没有该商品则添加
		if (cart == null){
			return cartDao.addCart(userId,itemId,num);
		}else {
			return updateCartNum(userId, itemId, num, cart);
		}
	}

	@Override
	public List<Cart> showCarts(int id) {
		List<Cart> carts = (List<Cart>)(List)commonDao.getAllByOtherId(Cart.class, id, "user.userId");
		return carts;
	}

	@Override
	public Boolean updateCartNum(int userId, int itemId, int num, Cart cart) {
		cart.setQuantity(num);
		commonDao.update(cart);
		return true;
	}

	@Override
	public Boolean deleteCart(int userId, int itemId) {
		Cart cart = cartDao.getCartByUserAndItem(userId, itemId);
		commonDao.delete(cart);
		return true;
	}
}
